﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using CommClass;


namespace DMS
{
    public partial class FrmMergeDo : DMS.FrmTemplate 
    {
        Report Rpt = new Report();
        MO mo = new MO(App.Ds);
        string mergenumber;
        string sqlstr;
        bool flag;
        public FrmMergeDo()
        {
            InitializeComponent();
            listBox1.SelectedIndex = 0;
           
            
        }

        //定义传递提单号
        private string sedonumber = null;
        public string SeDoNumber
        {
            get
            {
                return sedonumber;
            }
        }
       
       
        private void Form2_Load(object sender, EventArgs e)
        {
            //承运商下拉
            DataTable dt = mo.GetCarrierID();
            DataRow dr = dt.NewRow();
            dr["CarrierID"] = "0";
            dr["CarrierName"] = "请选择";
            dt.Rows.InsertAt(dr, 0);
            //下拉数据绑定
            cmbcarrierid.DataSource = dt;
            cmbcarrierid.DisplayMember = "CarrierName";
            cmbcarrierid.ValueMember = "CarrierID";
            //默认选中
            cmbcarrierid.SelectedIndex = 0;

            cmbsaletype.SelectedIndex = 0;

        }

        private void button1_Click(object sender, EventArgs e)
        {
            
            string vehiclenumber =txtbVehicleNumber .Text .Trim (); 
            string ordernumber = txtbOrderNumber.Text.Trim();
            string deliverynumber = txtbDeliveryNumber.Text.Trim();
            string prodname = txtbProduct.Text.Trim();
            string custname = txtbCustomer.Text.Trim();
            string address = txtbAddress.Text.Trim();
            string carrierid = cmbcarrierid.SelectedValue.ToString();
            string saletype = cmbsaletype.SelectedItem.ToString();
           
            //筛选条件组合
            sqlstr = ""; 
            if (vehiclenumber != "")
            {
                sqlstr = sqlstr + " and d.vehiclenumber='" + vehiclenumber+"'";
            }
            if (ordernumber != "")
            {
                sqlstr = sqlstr + " and d.ordernumber='" + ordernumber + "'"; 
            }
            if (deliverynumber != "")
            {
                sqlstr = sqlstr + " and d.deliverynumber='" + deliverynumber + "'";
            }
            if (prodname != "")
            {
                sqlstr = sqlstr + " and p.prodname like '%" + prodname + "%'";
            }
            if (custname != "")
            {
                sqlstr = sqlstr + " and d.custname like '%" + custname + "%'";
            }
            if (address != "")
            {
                sqlstr = sqlstr + " and d.deliveryaddress like '%" + address + "%'";
            }
            if (Int32.Parse(carrierid) > 0)
            {
                sqlstr = sqlstr + " and d.carrierid='" + carrierid + "'";
            }
            if (saletype != "")
            {
                sqlstr = sqlstr + " and d.saletype='" + saletype + "'";
            }

            //给datagridview绑定数据
            dgvdo.DataSource =mo.getDoData(sqlstr);
            
        }
        string checkvehiclenum;
        string carriername;
        string vehcount;
        bool result;
        private bool CheckVehilce()
        {
                      
            for (int i = 0; i < dgvdo.RowCount; i++)
            {
                //判断是否选中
                if (dgvdo.Rows[i].Cells[0].EditedFormattedValue.ToString() == "True")
                {
                    checkvehiclenum = dgvdo.Rows[i].Cells[3].Value.ToString();
                    carriername = dgvdo.Rows[i].Cells[5].Value.ToString();
                    vehcount = dgvdo.Rows[i].Cells[4].Value.ToString();
                }
            }
            for (int i = 0; i < dgvdo.RowCount; i++)
            {
                //判断是否选中
                if (dgvdo.Rows[i].Cells[0].EditedFormattedValue.ToString() == "True")
                {
                    if (checkvehiclenum != dgvdo.Rows[i].Cells[3].Value.ToString() || carriername != dgvdo.Rows[i].Cells[5].Value.ToString() || vehcount !=dgvdo.Rows[i].Cells[4].Value.ToString())
                    {
                        result = false;
                        break;
                    }
                    else
                    {
                        result = true;
                    }

                }
            }
            

            return result;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (!CheckVehilce())
            {
                MessageBox .Show ("不同车号车次或承运商不能被合并");
                return;

            }
            
            DataGridView gv = dgvdo;
            string vehnumber = txbvehnumber.Text.ToString();
            string remark = txbremark.Text.ToString();
            mergenumber = mo.AutoCreatMergeNumber("SH");  //获取合并拣货单号
            
            string sqlcase;
           
            if (vehnumber == "")
            {
                sqlcase = "";
            }
            else
            {
                sqlcase = ",vehiclenumber='" + vehnumber + "'";
            }
             //Math.Round(45.367,2)  
            string messageeee = "生成成功";
                using (SqlConnection conn = new SqlConnection(App.GetSqlConnection()))
                {
                    conn.Open();
                    using (SqlTransaction tran = conn.BeginTransaction()) //开始数据库事务。即创建一个事务对象tran  
                    {
                        using (SqlCommand cmd = new SqlCommand())
                        {
                            cmd.Connection = conn;
                            cmd.Transaction = tran; //获取或设置将要其执行的事务  
                            try
                            {
                                //保存主单
                                mo.SaveMergeHead111(mergenumber, remark, conn, cmd);
                                //保存明细
                                for (int i = 0; i < gv.RowCount; i++)
                                {
                                    //判断是否选中
                                    if (gv.Rows[i].Cells[0].EditedFormattedValue.ToString() == "True")
                                    {
                                        mo.SaveMergeEntry111(sqlcase, gv.Rows[i].Cells[1].Value.ToString(), mergenumber, conn, cmd);
                                    }

                                }
                                //执行按批次的先进先出，分配库存
                                //查询明细
                                DataTable dtt111 = mo.GetDOEntry(" a.[DeliveryNumber] in (select  [DONumber] from [t_MOEntry] where [MergeNumber] ='" + mergenumber + "' and [IsDeleted] = " + App.notfreeze + ") ", cmd);
                                //分配库存,必须是合格品，根据批次先进先出，如果批次有要求，则按批次来
                                if (dtt111.Rows.Count > 0)
                                {
                                    for (int j = 0; j < dtt111.Rows.Count; j++)
                                    {
                                        StringBuilder sqlsb = new StringBuilder();
                                        sqlsb.Append(" [StockUseableQty] >0  ");
                                        sqlsb.Append(" and  [ProdID] =  " + dtt111.Rows[j]["ProdID"].ToString() );
                                        sqlsb.Append(" and [StorageID] in (select [StorageID] from t_Storage where [freeze] =" + App.notfreeze + ") and [StorageID] in ( select a.StorageID from  t_Storage a,t_Kuqu b where  a.[KuquID] = b.[KuquID] and b.[StoreID]= " + dtt111.Rows[j]["StoreID"].ToString() + "   ) and StockPinZhiID =" + App.newstatus);
                                        if (dtt111.Rows[j]["Batch"] != null && dtt111.Rows[j]["Batch"].ToString() != "")
                                        {
                                            sqlsb.Append(" [Batch] =  '" + dtt111.Rows[j]["Batch"].ToString() + "' ");
                                        }
                                        DataTable dttstork = mo.GetStork(sqlsb.ToString(), " Batch,InputDate ", cmd);
                                       
                                        if (dttstork.Rows.Count == 0)
                                        {
                                            //插入出库明细,无货位，无批次
                                            mo.insertchukukucun(dtt111.Rows[j]["DOEntryID"].ToString(), null, dtt111.Rows[j]["OrderQty"].ToString(), null, null, null, "0", conn, cmd);
                                        }else
                                        {
                                            double shuliang = double.Parse(dtt111.Rows[j]["OrderQty"].ToString());

                                            for (int i = 0; i < dttstork.Rows.Count; i++)
                                            {
                                                double kucun = double.Parse(dttstork.Rows[i]["StockUseableQty"].ToString());
                                                if (shuliang <= kucun)
                                                {
                                                    //如果库存已经满足，跳出循环
                                                    mo.updateStork("StockUseableQty = "+(kucun-shuliang), dttstork.Rows[i]["StockTakingid"].ToString(), conn, cmd);
                                                    //插入出库明细
                                                    mo.insertchukukucun(dtt111.Rows[j]["DOEntryID"].ToString(), dttstork.Rows[i]["StorageID"].ToString(), Convert.ToString(shuliang), dttstork.Rows[i]["Batch"].ToString(), dttstork.Rows[i]["ProduceDate"].ToString(), dttstork.Rows[i]["StockPinZhiID"].ToString(), dttstork.Rows[i]["StockTakingid"].ToString(), conn, cmd);
                                                    break;
                                                }
                                                if (shuliang > kucun)
                                                {
                                                    //如果库存没有满足，继续分配别的库存
                                                    mo.updateStork("StockUseableQty = " + 0, dttstork.Rows[i]["StockTakingid"].ToString(), conn, cmd);
                                                    //插入出库明细
                                                    mo.insertchukukucun(dtt111.Rows[j]["DOEntryID"].ToString(), dttstork.Rows[i]["StorageID"].ToString(), dttstork.Rows[i]["StockUseableQty"].ToString(), dttstork.Rows[i]["Batch"].ToString(), dttstork.Rows[i]["ProduceDate"].ToString(), dttstork.Rows[i]["StockPinZhiID"].ToString(), dttstork.Rows[i]["StockTakingid"].ToString(), conn, cmd);
                                                }
                                                if ((i + 1) == dttstork.Rows.Count && shuliang > kucun)
                                                {
                                                    //插入出库明细,无货位，无批次
                                                    mo.insertchukukucun(dtt111.Rows[j]["DOEntryID"].ToString(), null, Convert.ToString(shuliang - kucun), null, null, null, "0", conn, cmd);
                                                }
                                                shuliang = shuliang - kucun;
                                               
                                            }
                                        }
                                    }

                                }


                              
                                 
                                tran.Commit();
                                conn.Close();

                                MessageBox.Show(messageeee);
                            }
                            catch
                            {

                                tran.Rollback();//如果执行不成功，发送异常，则执行rollback方法，回滚到事务操作开始之前。
                                conn.Close();
                                MessageBox.Show("生成失败！");
                            }

                        }
                    }

                }
          
            txbmegernumber.Text = mergenumber;
            txbvehnumber.Text = "";
            button3.Enabled = true;//激活打印按钮
            gv.DataSource = mo.getDoData(sqlstr);
            
        }

             

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            this.button2.Enabled = true;
            
        }

        private void button3_Click(object sender, EventArgs e)
        {
            DataTable dt = mo.GetMergeHead(mergenumber);
            Rpt.SourceData = mo.GetMergeTitle(mergenumber).DefaultView;
            Rpt.ReportName = @"Report\RptMergeDo.rdlc";
            Rpt.Parameters.Clear();
            Rpt.Parameters.Add("mergenumber", dt.Rows[0][0].ToString());
            Rpt.Parameters.Add("vehnumber", dt.Rows[0][1].ToString());
            Rpt.Parameters.Add("saletype", dt.Rows[0][4].ToString());
            Rpt.Parameters.Add("remark", dt.Rows[0][5].ToString());
            Rpt.Parameters.Add("countdo", dt.Rows[0][3].ToString());
            Rpt.Parameters.Add("carrier", dt.Rows[0][2].ToString());
            Rpt.Parameters.Add("donumber", mo.GetCountDo(mergenumber));
            mo.UpdatePrint(mergenumber);
            for (int i = 0; i < int.Parse(listBox1.SelectedItem.ToString()); i++)
            {
                Rpt.Print();
            }
            //Report Rpt1 = new Report();
            //Rpt1.SourceData = mo.GetVehilceEntry(mergenumber).DefaultView;
            //Rpt1.ReportName = @"Report\RptVehicleEntry.rdlc";

            //Rpt1.Print();
            button3.Enabled = false;
        }

        private void dataGridView1_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            //查看提单明细信息
            int row = dgvdo.Rows[e.RowIndex].Index;
            sedonumber = dgvdo.Rows[row].Cells[1].Value.ToString();//当前选定的提货单号
            FrmDoEntry form = new FrmDoEntry();
            form.ReDoNumber = sedonumber;
            form.ShowDialog();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            DataTable dt = (DataTable)dgvdo.DataSource;
            if (dt != null && dt.Rows.Count > 0)
            {
                DataGridViewCheckBoxCell checkCell;
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    //判断是否选中
                    checkCell = (DataGridViewCheckBoxCell)this.dgvdo.Rows[i].Cells[0];

                    checkCell.Value = true;

                }
                this.button2.Enabled = true;
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            DataTable dt = (DataTable)dgvdo.DataSource;
            if (dt != null && dt.Rows.Count > 0)
            {
                DataGridViewCheckBoxCell checkCell;
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    //判断是否选中
                    checkCell = (DataGridViewCheckBoxCell)this.dgvdo.Rows[i].Cells[0];

                    checkCell.Value = false;

                }
                this.button2.Enabled = false;
            }
        }

      
    }
}
